package com.example.zhapp_java.activities;

import android.app.DatePickerDialog;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.zhapp_java.R;
import com.example.zhapp_java.adapters.MilestoneAdapter;
import com.example.zhapp_java.adapters.PhaseAdapter;
import com.example.zhapp_java.api.ApiClient;
import com.example.zhapp_java.api.ApiService;
import com.example.zhapp_java.models.Milestone;
import com.example.zhapp_java.models.Phase;
import com.example.zhapp_java.models.Project;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

// ProjectDetailActivity.java
public class ProjectDetailActivity extends AppCompatActivity {
    private String projectNo;
    private Project currentProject;

    // 左右分栏布局
    private RecyclerView phaseRecyclerView;
    private RecyclerView milestoneRecyclerView;
    private PhaseAdapter phaseAdapter;
    private MilestoneAdapter milestoneAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_detail);

        projectNo = getIntent().getStringExtra("PROJECT_NO");

        // 初始化项目信息编辑
        EditText etProjectNo = findViewById(R.id.etProjectNo);
        EditText etProjectDesc = findViewById(R.id.etProjectDesc);

        // 初始化阶段列表
        phaseRecyclerView = findViewById(R.id.phaseRecyclerView);
        phaseRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        phaseAdapter = new PhaseAdapter(new ArrayList<>(), this::onPhaseSelected);
        phaseRecyclerView.setAdapter(phaseAdapter);

        // 初始化里程碑列表
        milestoneRecyclerView = findViewById(R.id.milestoneRecyclerView);
        milestoneRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        milestoneAdapter = new MilestoneAdapter(new ArrayList<>());
        milestoneRecyclerView.setAdapter(milestoneAdapter);

        // 加载项目详情
        loadProjectDetails();

        // 设置按钮事件
        findViewById(R.id.btnAddPhase).setOnClickListener(v -> showAddPhaseDialog());
        findViewById(R.id.btnAddMilestone).setOnClickListener(v -> showAddMilestoneDialog());
        findViewById(R.id.btnSave).setOnClickListener(v -> saveProject());
    }


    private void loadPhases() {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<List<Phase>> call = api.getPhases(projectNo);
        call.enqueue(new Callback<List<Phase>>() {
            @Override
            public void onResponse(Call<List<Phase>> call, Response<List<Phase>> response) {
                if (response.isSuccessful()) {
                    phaseAdapter.updateList(response.body());
                    if (!response.body().isEmpty()) {
                        loadMilestones(response.body().get(0).getPhraseId());
                    }
                }
            }

            @Override
            public void onFailure(Call<List<Phase>> call, Throwable t) {
                // 错误处理
            }
        });
    }

    private void onPhaseSelected(Phase phase) {
        loadMilestones(phase.getPhraseId());
    }


    // 在ProjectDetailActivity类中添加以下方法

    private void loadMilestones(String phraseId) {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<List<Milestone>> call = api.getMilestones(projectNo, phraseId);
        call.enqueue(new Callback<List<Milestone>>() {
            @Override
            public void onResponse(Call<List<Milestone>> call, Response<List<Milestone>> response) {
                if (response.isSuccessful()) {
                    milestoneAdapter.updateList(response.body());
                }
            }

            @Override
            public void onFailure(Call<List<Milestone>> call, Throwable t) {
                // 错误处理
            }
        });
    }

    private void saveProject() {
        EditText etProjectDesc = findViewById(R.id.etProjectDesc);
        String newDesc = etProjectDesc.getText().toString();

        if (currentProject == null) {
            Toast.makeText(this, "项目信息未加载", Toast.LENGTH_SHORT).show();
            return;
        }

        // 更新项目对象
        currentProject.setProjectDesc(newDesc);

        // 调用API保存修改
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = api.updateProject(currentProject);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(ProjectDetailActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();
                } else {
                    Toast.makeText(ProjectDetailActivity.this,
                            "保存失败: " + response.code(),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(ProjectDetailActivity.this,
                        "保存失败: " + t.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 添加阶段对话框
    private void showAddPhaseDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_phase, null);

        EditText etPhaseId = dialogView.findViewById(R.id.etPhaseId);
        EditText etBudget = dialogView.findViewById(R.id.etPhaseBudget);
        EditText etDesc = dialogView.findViewById(R.id.etPhaseDesc);

        builder.setView(dialogView)
                .setTitle("添加阶段")
                .setPositiveButton("添加", (dialog, id) -> {
                    Phase newPhase = new Phase();
                    newPhase.setPhraseId(etPhaseId.getText().toString());
                    newPhase.setPhraseBudget(Integer.parseInt(etBudget.getText().toString()));
                    newPhase.setPhraseDesc(etDesc.getText().toString());

                    addPhase(newPhase);
                })
                .setNegativeButton("取消", null);

        builder.create().show();
    }

    private void addPhase(Phase phase) {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = api.createPhase(projectNo, phase);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    loadPhases(); // 刷新阶段列表
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                // 错误处理
            }
        });
    }
    private void showAddMilestoneDialog() {
        if (phaseAdapter.getSelectedPosition() == -1) {
            Toast.makeText(this, "请先选择一个阶段", Toast.LENGTH_SHORT).show();
            return;
        }

        Phase selectedPhase = phaseAdapter.getSelectedPhase();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_milestone, null);

        EditText etMilestoneId = dialogView.findViewById(R.id.etMilestoneId);
        EditText etDate = dialogView.findViewById(R.id.etDate);
        EditText etRemarks = dialogView.findViewById(R.id.etRemarks);

        // 日期输入辅助（可选：添加日期选择器）
        etDate.setOnClickListener(v -> {
            // 实现日期选择器
            showDatePicker(etDate);
        });

        builder.setView(dialogView)
                .setTitle("添加里程碑")
                .setPositiveButton("添加", (dialog, id) -> {
                    Milestone newMilestone = new Milestone();
                    newMilestone.setProjectNo(projectNo);
                    newMilestone.setPhraseId(selectedPhase.getPhraseId());
                    newMilestone.setMilestoneId(etMilestoneId.getText().toString());

                    // 解析日期（简化处理，实际应使用日期选择器）
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        Date date = sdf.parse(etDate.getText().toString());
                        newMilestone.setMilestoneDate(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        Toast.makeText(this, "日期格式错误", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    newMilestone.setMilestoneRemarks(etRemarks.getText().toString());
                    addMilestone(newMilestone);
                })
                .setNegativeButton("取消", null);

        builder.create().show();
    }

    private void showDatePicker(EditText etDate) {
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePicker = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    String selectedDate = String.format(Locale.getDefault(),
                            "%04d-%02d-%02d", year, month + 1, dayOfMonth);
                    etDate.setText(selectedDate);
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        datePicker.show();
    }

    private void addMilestone(Milestone milestone) {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<Void> call = api.createMilestone(milestone.getProjectNo(), milestone.getPhraseId(), milestone);
        call.enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.isSuccessful()) {
                    // 刷新当前阶段的里程碑
                    onPhaseSelected(phaseAdapter.getSelectedPhase());
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                Toast.makeText(ProjectDetailActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loadProjectDetails() {
        // 加载项目基本信息
        ApiService api = ApiClient.getClient().create(ApiService.class);
        Call<Project> projectCall = api.getProject(projectNo);
        projectCall.enqueue(new Callback<Project>() {
            @Override
            public void onResponse(Call<Project> call, Response<Project> response) {
                if (response.isSuccessful()) {
                    currentProject = response.body();

                    // 更新项目信息到UI
                    EditText etProjectNo = findViewById(R.id.etProjectNo);
                    EditText etProjectDesc = findViewById(R.id.etProjectDesc);

                    if (currentProject != null) {
                        etProjectNo.setText(currentProject.getProjectNo());
                        etProjectDesc.setText(currentProject.getProjectDesc());
                    }

                    loadPhases();
                } else {
                    // 处理错误响应
                    Toast.makeText(ProjectDetailActivity.this,
                            "加载项目信息失败: " + response.code(),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Project> call, Throwable t) {
                // 错误处理
                Toast.makeText(ProjectDetailActivity.this,
                        "网络错误: " + t.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}